import React, { useState, useMemo, useEffect, useRef } from "react";
import "./index.scss";
import { Button, Card, Tabs, Popup, Ellipsis, Badge } from "antd-mobile";
import TaskList from "./taskList";
import ProjApprovalNode from "./detail/projApprovalNode";
import FileCountChart from "./detail/fileCountChart";
import { queryHomeData, pqscommonSetting_query_page } from "src/api/home";
import axios from "src/api/index";
import { inject, observer } from "mobx-react";
import Cookies from "js-cookie";
import { ISProduct } from "src/config";
import Toast from "src/pages/components/clickableToast";

const viewMenu = [
    "/PreSubmit",
    "/MeasureDesign",
    "/ProcessDoc",
    "/DeliveryofCompletion",
    "/WorkStartStandard",
];

export default observer(props => {
    const [homeData, setHomeData] = useState({
        preExamList: [], // 前期报审
        desMeanList: [], // 设计测量
        processFileList: [], // 过程文件
        onCompletionList: [], // 交工完成
        onStandardList: [], // 开工标准化
    });
    const [activityKey, setActivityKey] = useState("");
    const [visible, setVisible] = useState(false);
    const [count, setCount] = useState("");
    const { store, history } = props;

    useEffect(() => {
        // 正式环境
        if (ISProduct) {
            loginByJwt();
        } else {
            getData();
        }
    }, []);

    const loginByJwt = () => {
        const jwt = history.location.search?.split("?")[1]?.split("=")?.[1];
        if (jwt) {
            Cookies.set("CRBIMSSOJWT", jwt);
            autoLogin();
        } else {
            autoLogin();
        }
    };

    const onFinish = values => {
        const userMsg = {
            userId: "1551638",
            password: "4c96e5ce31cf32470926e81cd96183cd",
        };
        Toast.show({
            icon: "loading",
            content: "登录中…",
        });
        props.store.user.login(userMsg).then(res => {
            if (res.code === 200) {
                Toast.show({
                    icon: "success",
                    content: res.msg,
                });
                getData();
            }
        });
    };
    const autoLogin = () => {
        Toast.show({
            icon: "loading",
            content: "登录中…",
        });
        props.store.user.TKYlogin().then(res => {
            if (res.code === 200) {
                getData();
            } else {
                Toast.show({
                    icon: "fail",
                    content: res.msg,
                });
            }
        });
    };

    const getHomeData = (typeId = 3) => {
        return queryHomeData(typeId).then(
            res => {
                return Promise.resolve(res.data);
            },
            err => {
                console.log(err);
            },
        );
    };

    const getData = () => {
        getHomeData().then(allData => {
            pqscommonSetting_query_page(1).then(result => {
                let _homeData = { ...homeData };
                const menuList = result.data.filter(item => item.pid === 0) || [];
                const preExamList = menuList.filter(item => item.modelName.includes("前期报审"));
                _homeData.preExamList = matchData(allData, preExamList);
                const desMeanList = menuList.filter(item =>
                    item.modelName.includes("测量及设计交接"),
                );
                _homeData.desMeanList = matchData(allData, desMeanList);
                const processFileList = menuList.filter(item =>
                    item.modelName.includes("过程文件"),
                );
                _homeData.processFileList = matchData(allData, processFileList);
                const onCompletionList = menuList.filter(item =>
                    item.modelName.includes("交竣工验收"),
                );
                _homeData.onCompletionList = matchData(allData, onCompletionList);
                const onStandardList = menuList.filter(item =>
                    item.modelName.includes("开工标准化"),
                );
                _homeData.onStandardList = matchData(allData, onStandardList);
                setHomeData(_homeData);
            });
        });
    };

    const matchData = (allData = [], list = []) => {
        return list.map(item => {
            const flag = allData.find(el => item.tableId === el.moduleId);
            if (flag) {
                return {
                    ...flag,
                    moduleName: item.label,
                };
            } else {
                return {
                    moduleId: item.tableId,
                    moduleName: item.label,
                    scount: 0,
                };
            }
        });
    };

    const homeCardData = useMemo(() => {
        return [
            {
                title: "前期报审",
                data: homeData.preExamList,
                tableId: 1000008142,
            },
            {
                title: "测量及设计交接",
                data: homeData.desMeanList,
                tableId: 1000008143,
            },
            {
                title: "过程文件",
                data: homeData.processFileList,
                tableId: 1000008144,
            },
            {
                title: "交竣工验收",
                data: homeData.onCompletionList,
                tableId: 1000008145,
            },
            {
                title: "开工标准化",
                data: homeData.onStandardList,
                tableId: 1000008167,
            },
        ];
    }, [homeData]);

    const getTabs = useMemo(() => {
        let allMenus = [...store.user.menuList];
        allMenus.unshift({
            treeName: "待办",
            jspath: "/message",
        });
        return allMenus.filter(
            tab => !["/Homeforrails", "/SysConfig", "/SealTask"].includes(tab.jspath),
        );
    }, [store.user.menuList]);

    const activeTab = useMemo(() => {
        return getTabs.find(tab => tab.jspath === activityKey);
    }, [activityKey]);

    const changeTab = activityKey => {
        if (["/SignTask", "/message"].includes(activityKey)) {
            history.push(activityKey);
            return;
        }
        setActivityKey(activityKey);
        setVisible(visible => !visible);
    };

    const CardMenus = useMemo(() => {
        let menuList =
            getTabs
                .filter(menus => viewMenu.includes(menus.jspath))
                .map(menus => {
                    const data = menus.data
                        .map(secondMenu => {
                            const name = secondMenu.jspath.split("/")[2] || "";
                            let iconPath;
                            try {
                                iconPath = require(`src/assets/img/${name}.png`);
                            } catch (error) {
                                //未加载到配置图标 过滤
                                return null;
                            }
                            return {
                                ...secondMenu,
                                iconPath,
                            };
                        })
                        .filter(data => data);
                    return {
                        ...menus,
                        data,
                        className: `${
                            menus.jspath.split("/")[1]?.toLocaleLowerCase() || ""
                        } menus-list`,
                    };
                }) || [];
        return menuList;
    }, [getTabs]);

    const handlePresubmitMenu = menu => {
        menu.jspath && history.push(menu.jspath);
    };

    return (
        <div className="home-page">
            <Tabs
                activeKey={activityKey}
                onChange={changeTab}
                style={{
                    "--active-title-color": "#d72b3e",
                    "--active-line-color": "none",
                    fontWeight: 600,
                }}
            >
                {getTabs.map(tab => {
                    const title =
                        tab.jspath === "/message" ? (
                            <Badge content={count} style={{ "--right": "-10px", "--top": "8px" }}>
                                {tab.treeName}
                            </Badge>
                        ) : (
                            tab.treeName
                        );
                    return <Tabs.Tab title={title} key={tab.jspath} />;
                })}
            </Tabs>
            <div className="home-page-content">
                <Card
                    bodyClassName={"customBody"}
                    title=""
                    style={{ position: "absolute", left: "-9999px" }}
                >
                    <TaskList store={store} setCount={setCount} />
                </Card>
                <Card bodyClassName={"customBody"} title="项目报审节点">
                    <ProjApprovalNode store={store} />
                </Card>
                <Card bodyClassName={"customBody"} title="文件数量统计">
                    <FileCountChart homeCardData={homeCardData} />
                </Card>
                {CardMenus.map(menu => {
                    return (
                        <Card
                            key={menu.treeId}
                            className={menu.className}
                            bodyClassName={"customBody"}
                            title={menu.treeName}
                        >
                            {menu.data.map(secMenu => {
                                return (
                                    <div
                                        className="menu-item"
                                        key={secMenu.tableId}
                                        onClick={e => handlePresubmitMenu(secMenu)}
                                    >
                                        <img src={secMenu.iconPath} alt="" />
                                        <div className="title">{secMenu.treeName}</div>
                                    </div>
                                );
                            })}
                        </Card>
                    );
                })}
            </div>
            <Popup
                visible={visible}
                onMaskClick={() => {
                    setVisible(false);
                    setActivityKey("");
                }}
                onClose={() => {
                    setVisible(false);
                    setActivityKey("");
                }}
                bodyStyle={{ height: "60vh" }}
                getContainer={null}
                showCloseButton={true}
                className="home-pop"
            >
                <h2 className="title">{activeTab?.treeName}</h2>
                <div className="list">
                    {activeTab?.data?.map(table => {
                        return (
                            <div
                                className="list-item"
                                key={table.id}
                                onClick={() => table.jspath && history.push(table.jspath)}
                            >
                                {table.treeName}
                            </div>
                        );
                    })}
                </div>
            </Popup>
        </div>
    );
});
